package com.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.List;

public class XmlUtil {
    private static String attr1 = "name";
    private static String attr2 = "value";
    private static Document document = null;
    private static String eleName;

    public static String getRootUrl(String filename, String elename) {
        try {
            document = getDocument(filename);
            Element root = document.getRootElement();
            eleName = root.element(elename).getTextTrim();
            System.out.println("获取" + elename + "值:" + eleName);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return eleName;
    }

    public static String getSheetName(String filename, String nodename , String eleName) {
        try {
            document = getDocument(filename);
            Element root = document.getRootElement();
            List<Element> rootList = root.elements();
            if (rootList.size() > 0) {
                for (int i = 0; i < rootList.size(); i++) {
                    if (nodename.equalsIgnoreCase(rootList.get(i).getName())) {
                        List<Element> secondList = rootList.get(i).elements();
                        if (secondList.size() > 0) {
                            for (int j = 0; j < secondList.size(); j++) {
                                if(eleName.equalsIgnoreCase(secondList.get(j).attributeValue(attr1))){
                                    eleName = secondList.get(j).attributeValue(attr2);
                                    j = secondList.size()-1;
                                }
                            }
                        }
                    }
                    i = rootList.size()-1;
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return eleName;
    }

    public static Document addElementsXmlFile(String filename) {
        Document document = null;
        try {
            document = getDocument(filename);

            Element root = document.getRootElement();
            Element rootUrl = root.addElement("rootUrl");
            rootUrl.setText("http://crmgateway-test.victorplus.cn");
            // headers element
            root.addComment("This is a test for dom4j add headers！");
            Element headers = root.addElement("headers");

            headers.addComment("This is a test for dom4j add header！");
            Element header1 = headers.addElement("header");
            header1.addAttribute("name", "name1");
            header1.addAttribute("value", "value1");

            Element header2 = headers.addElement("header");
            header2.addAttribute("name", "name2");
            header2.addAttribute("value", "value2");
            root.addComment("This is a test for dom4j add params！");
            Element params = root.addElement("params");
            params.addComment("This is a test for dom4j add param！");
            Element param = params.addElement("param");
            param.addAttribute("name", "name");
            param.addAttribute("value", "value");

            saveDocument(document, new File(filename));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return document;
    }

    //文件名，节点名称，定位节点属性，定位节点属性值，修改节点属性，修改后节点属性值
    public static void modifyXmlFile(String filename, String nodename, String attr1value, String attr2value) {
//        Document document = null;
        try {
            document = getDocument(filename);
            Element root = document.getRootElement();
            List<Element> rootList = root.elements();
            if (rootList.size() > 0) {
                for (int i = 0; i < rootList.size(); i++) {
                    Element secondEle = rootList.get(i);
                    if (secondEle.getName().equals(nodename)) {
                        List<Element> secondList = secondEle.elements();
                        if (secondList.size() > 0) {
                            for (int j = 0; j < secondList.size(); j++) {
                                Element thirdEle = secondList.get(j);
                                if (thirdEle.attributeValue(attr1).contains(attr1value)) {
                                    thirdEle.attribute(attr2).setValue(attr2value);
                                    saveDocument(document, new File(filename));
                                    j = secondList.size() - 1;
                                } else if (!thirdEle.attributeValue(attr1).contains(attr1value) && !attr1value.contains("vkey") && !attr1value.contains("Content-Type") && j == secondList.size() - 1) {
                                    Element addParam = secondEle.addElement(secondList.get(j).getName());
                                    addParam.addAttribute(attr1, attr1value);
                                    addParam.addAttribute(attr2, attr2value);
                                    saveDocument(document, new File(filename));
                                }
                            }
                        } /*else {
                            System.out.println("------secondList.size()不大于0------");
                        }*/
                        i = rootList.size() - 1;
                    } /*else {
                        System.out.println("------secondEle.getName()不满足条件------" + secondEle.getName()); //属性
                    }*/
                }
            } else {
                System.out.println("------rootList.size()不大于0------" + rootList.size());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static Document getDocument(String filename) throws DocumentException {
        SAXReader reader = new SAXReader();
        InputStream inFile = null;
        try {
            inFile = new FileInputStream(filename);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        InputStreamReader ir = null;
        try {
            ir = new InputStreamReader(inFile, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Document document = reader.read(ir);
        return document;
    }

    public static Document generateDocumentByMethod() {
        Document document = DocumentHelper.createDocument();
        // ProcessingInstruction
/*        Map<String, String> inMap = new HashMap<String, String>();
        inMap.put("type", "text/xsl");
        inMap.put("href", "students.xsl");
        document.addProcessingInstruction("xml-stylesheet", inMap);*/
        return document;
    }


    public static void saveDocument(Document document, File outputXml) {
        try {
            // 美化格式
            OutputFormat format = OutputFormat.createPrettyPrint();
           /*// 缩减格式
           OutputFormat format = OutputFormat.createCompactFormat();*/
            // 指定XML编码
            format.setEncoding("UTF-8");
            XMLWriter output = new XMLWriter(new FileWriter(outputXml), format);
            output.write(document);
            output.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }


    public static void main(String[] args) {
        com.utils.XmlUtil umlUtil = new com.utils.XmlUtil();
//        Document doc = umlUtil.generateDocumentByMethod();
//        Document doc = umlUtil.addElementsXmlFile("testXml2.xml");
        System.out.println(getSheetName("testng1.xml", "test" , "sheetName"));
        /*for (int i = 0; i <= 0; i++) {
            modifyXmlFile("testXml2.xml", "params", String.valueOf(i), String.valueOf(i + 1));
        }
        modifyXmlFile("testXml2.xml", "params", "appCode", "9999");*/
//        getRootUrl("testXml2.xml","rootUrl");
//        String imgFile = "pic/image.jpeg";//待处理的图片
//        String imgbese=getImgStr(imgFile);
//        System.out.println(imgbese.length());
//        System.out.println(imgbese);

    }
}
